from scipy.fft import fft
import numpy as np

def read_file(file_path):
    with open(file_path, 'r') as file:
        content = file.readlines()
    data = [float(x.strip()) for x in content]
    return data

def get_fft(data):
    # 计算频域信号
    n = len(data)
    freqs = np.fft.fftfreq(n)
    mask = freqs > 0
    fft_data = fft(data)
    fft_abs = np.abs(fft_data[mask])
    fft_norm = fft_abs / np.max(fft_abs)
    return fft_norm

def get_similarity(file_path1, file_path2, num_freqs=10):
    # 读取数据
    data1 = read_file(file_path1)
    data2 = read_file(file_path2)
    # 计算频域信号
    fft_norm1 = get_fft(data1)
    fft_norm2 = get_fft(data2)
    # 提取前N个主要频率的振幅值
    freq_idx1 = np.argsort(fft_norm1)[::-1][:num_freqs]
    freq_idx2 = np.argsort(fft_norm2)[::-1][:num_freqs]
    freq_amp1 = fft_norm1[freq_idx1]
    freq_amp2 = fft_norm2[freq_idx2]
    # 归一化处理
    freq_amp1 = freq_amp1 / np.max(freq_amp1)
    freq_amp2 = freq_amp2 / np.max(freq_amp2)
    # 计算欧几里得距离
    distance = np.linalg.norm(freq_amp1 - freq_amp2)
    # 计算相似度
    similarity = 1 / (1 + distance)
    return similarity


similarity = get_similarity('7.txt', '8.txt')
print(similarity)